package com.umerclass.frame.ui.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.ColorInt;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.slidingpanelayout.widget.SlidingPaneLayout;

import com.umerclass.AppDroid;
import com.umerclass.R;
import com.umerclass.frame.asynctask.TaskExecutor;
import com.umerclass.frame.model.InfoResult;
import com.umerclass.frame.model.MsgBean;
import com.umerclass.frame.okhttp.OkEntityListRequest;
import com.umerclass.frame.okhttp.OkEntityRequest;
import com.umerclass.frame.okhttp.OkHttpTask;
import com.umerclass.frame.okhttp.OkSimpleRequest;
import com.umerclass.frame.okhttp.SimpleOkHttpListener;
import com.umerclass.frame.ui.barlibrary.ImmersionBar;
import com.umerclass.ui.user.UserLoginActivity;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.lang.reflect.Field;
import butterknife.ButterKnife;

/**
 * Created by jack
 * 基类
 */

public abstract class BaseActivity extends AppCompatActivity implements SlidingPaneLayout.PanelSlideListener{

    public static boolean isForeground = false;
    private EventBus eventBus;
    private InputMethodManager inputMethodManager;
    private Toast toast = null;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    InfoResult infoResult = (InfoResult) msg.obj;
                    int state = infoResult.getState();
                    if(state == -4){
                        Intent i = new Intent(BaseActivity.this, UserLoginActivity.class);
                        i.putExtra("flag",3);
                        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                        startActivity(i);
                        finish();
                    }else{
                        if(infoResult.isSuccess()){
                            onSuccess(infoResult.getTag(),infoResult);
                        }else {
                            onFail(infoResult.getTag(),infoResult);
                        }
                    }
                    break;
                default:break;
            }
        }
    };

    //-------------------------- okhttp -----------------------------//

    public <T> void requestOkhttpEntityList(OkEntityListRequest<T> okEntityListRequest){
        SimpleOkHttpListener simpleOkHttpListener = new SimpleOkHttpListener(){
            @Override
            public void dataSucceed(int what, InfoResult t) {
                super.dataSucceed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }

            @Override
            public void dataFailed(int what, InfoResult t) {
                super.dataFailed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }
        };
        OkHttpTask okHttpTask = new OkHttpTask(okEntityListRequest,simpleOkHttpListener);
        TaskExecutor.getInstance().start(okHttpTask);
    }

    public <T> void requestOkhttpEntity(OkEntityRequest<T> okEntityRequest){
        SimpleOkHttpListener simpleOkHttpListener = new SimpleOkHttpListener(){
            @Override
            public void dataSucceed(int what, InfoResult t) {
                super.dataSucceed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }

            @Override
            public void dataFailed(int what, InfoResult t) {
                super.dataFailed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }
        };
        OkHttpTask okHttpTask = new OkHttpTask(okEntityRequest,simpleOkHttpListener);
        TaskExecutor.getInstance().start(okHttpTask);
    }

    public <T> void requestOkhttpSimple(OkSimpleRequest<T> tOkSimpleRequest){
        SimpleOkHttpListener simpleOkHttpListener = new SimpleOkHttpListener(){
            @Override
            public void dataSucceed(int what, InfoResult t) {
                super.dataSucceed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }

            @Override
            public void dataFailed(int what, InfoResult t) {
                super.dataFailed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }
        };
        OkHttpTask okHttpTask = new OkHttpTask(tOkSimpleRequest,simpleOkHttpListener);
        TaskExecutor.getInstance().start(okHttpTask);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            AppDroid.getInstance().finishActivity(this);
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        initSwipeBackFinish();
        super.onCreate(savedInstanceState);
        //setStatusBarColor(getColor(this,R.color.colorPrimary));
        //把设置布局文件的操作交给继承的子类
        setContentView(getLayoutResId());
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        ButterKnife.bind(this);
        setScreenVertical(this);
        AppDroid.getInstance().addActivity(this);
        eventBus = EventBus.getDefault();
        eventBus.register(this);
        //初始化沉浸式
        initImmersionBar();
        init();
        loadData();
    }

    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (eventBus != null) {
            eventBus.unregister(this);
        }
        AppDroid.getInstance().finishActivity(this);
        ButterKnife.bind(this).unbind();
        if (isImmersionBarEnabled()) {
            ImmersionBar.with(this).destroy();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlerMeg(MsgBean msgBean) {

    }

    protected void initImmersionBar() {
        if (isImmersionBarEnabled()) {
            //在BaseActivity里初始化
            //ImmersionBar.with(this).init();
            ImmersionBar.with(this).navigationBarColor(R.color.colorPrimary).init();
        }
    }

    public void hideSoftKeyBoard() {
        View localView = getCurrentFocus();
        if (this.inputMethodManager == null) {
            this.inputMethodManager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
        }
        if ((localView != null) && (this.inputMethodManager != null)) {
            this.inputMethodManager.hideSoftInputFromWindow(localView.getWindowToken(), 2);
        }
    }

    /**
     * 初始化滑动返回
     */
    private void initSwipeBackFinish() {
        if (isSupportSwipeBack()) {
            SlidingPaneLayout slidingPaneLayout = new SlidingPaneLayout(this);
            //通过反射改变mOverhangSize的值为0，这个mOverhangSize值为菜单到右边屏幕的最短距离，默认
            //是32dp，现在给它改成0
            try {
                //mOverhangSize属性，意思就是左菜单离右边屏幕边缘的距离
                Field f_overHang = SlidingPaneLayout.class.getDeclaredField("mOverhangSize");
                f_overHang.setAccessible(true);
                //设置左菜单离右边屏幕边缘的距离为0，设置全屏
                f_overHang.set(slidingPaneLayout, 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
            slidingPaneLayout.setPanelSlideListener(this);
            //slidingPaneLayout.setSliderFadeColor(getColor(this,android.R.color.transparent));
            slidingPaneLayout.setSliderFadeColor(getResources().getColor(android.R.color.transparent));
            // 左侧的透明视图
            View leftView = new View(this);
            leftView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            slidingPaneLayout.addView(leftView, 0);  //添加到SlidingPaneLayout中
            // 右侧的内容视图
            ViewGroup decor = (ViewGroup) getWindow().getDecorView();
            ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
            decorChild.setBackgroundColor(getResources().getColor(android.R.color.white));
            decor.removeView(decorChild);
            decor.addView(slidingPaneLayout);
            // 为 SlidingPaneLayout 添加内容视图
            slidingPaneLayout.addView(decorChild, 1);
        }
    }


    public void showToast(String msg) {
        if (toast == null) {
            toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }

    public int getColor(Context context, int id) {
        return ContextCompat.getColor(context, id);
    }

    /**
     * 跳转到某个Activity
     *
     * @param activity
     * @param targetActivity
     */
    public void switchTo(Activity activity, Class<? extends Activity> targetActivity, boolean finish) {
        switchTo(activity, new Intent(activity, targetActivity),finish);
    }

    public void switchTo(Activity activity, Intent intent, boolean finish) {
        activity.startActivity(intent);
        if(finish){
            finish();
        }
        //overridePendingTransition(R.anim.alpha_out, R.anim.alpha_in);
    }

    /**
     * 设置Activity的显示方向为横向
     *
     * @param activity
     */
    private void setScreenHorizontal(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    /**
     * 设置Activity的显示方向为垂直方向
     *
     * @param activity
     */
    private void setScreenVertical(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    public void onPanelSlide(View panel, float slideOffset) {

    }

    @Override
    public void onPanelOpened(View panel) {
        finish();
        this.overridePendingTransition(0, R.anim.out_to_right);
    }

    @Override
    public void onPanelClosed(View panel) {

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void setStatusBarColor(@ColorInt int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            final Window window = getWindow();
            if (window != null) {
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(color);
            }
        }
    }

    // -------------------- BaseActivity的辅助封装 --------------------- //

    public abstract boolean isImmersionBarEnabled();

    /**
     * 是否支持滑动返回
     *
     * @return
     */
    public abstract boolean isSupportSwipeBack();

    /**
     * 返回当前Activity布局文件的id
     *
     * @return
     */
    public abstract int getLayoutResId();

    /**
     * 初始化的一些操作
     */
    public abstract void init();

    /**
     * 加载网络数据
     */
    public abstract void loadData();

    /**
     * 网络数据返回成功
     */
    protected abstract void onSuccess(int what, InfoResult t);

    /**
     * 网络数据返回失败
     */
    protected abstract void onFail(int what,InfoResult t);

    public EventBus getEventBus() {
        return eventBus;
    }

    private Dialog progressDialog;
    private TextView tipTextView;
    public void showProgress(String message) {
        showProgress(message, true);
    }

    public void showProgress(String message, boolean cancelable) {
        if (progressDialog == null) {
            progressDialog = createLoadingDialog(message);
        }
        else if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        if (!TextUtils.isEmpty(message)) {
            tipTextView.setText(message);
        }
        else {
            tipTextView.setText(getString(R.string.load_text));
        }
        progressDialog.setCancelable(cancelable);
        progressDialog.show();
    }


    /**
     * 得到自定义的progressDialog
     *
     * @param msg
     * @return
     */
    private Dialog createLoadingDialog(String msg) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.dialog_loading,
                null);
        tipTextView = (TextView) v.findViewById(R.id.tipTextView);
        if (!TextUtils.isEmpty(msg)) {
            tipTextView.setText(msg);
        }
        Dialog loadingDialog = new Dialog(this,
                R.style.loading_dialog);
        loadingDialog.setCancelable(true);
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.setContentView(v);
        return loadingDialog;
    }

    public void hideProgress() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    private Dialog loading_dialog;
    public void showDialog(String message){
        loading_dialog = new AlertDialog.Builder(this).setMessage(message).create();
        loading_dialog.show();
    }

    public void hideDialog(){
        if(loading_dialog!=null){
            loading_dialog.dismiss();
        }
    }
}
